import { history } from 'umi';
import { message } from 'antd';
import api from '../../services';
const { queryCategory, queryTag, queryAllArticle, queryArticles, viewArticle } = api;
export default {
    namespace: 'homePage',
    state: {
        categoryList: [],
        tagList: [],
        articleList: [],
        total: 0,
    },

    subscriptions: {
        setupHistory({ dispatch, history }) {  // eslint-disable-line
            return history.listen(({ pathname, state }) => {
                if (pathname === '/homePage') {
                    dispatch({ type: "queryCategory" });
                    dispatch({ type: "queryTag", payload: { categoryId: 0 } })
                    dispatch({ type: "queryAllArticle", payload: { categoryId: 0, page: 1, pageSize: 10 } })
                    return;
                }
            })
        },
    },
    effects: {
        *queryCategory({ }, { put, call, select }) {
            const result = yield call(queryCategory);
            if (result.code === 0) {
                yield put({ type: "updateState", payload: { categoryList: result.data } });
            }
            else {
                message.error(result.message, 1);
            }
        },
        *queryTag({ payload }, { put, call, select }) {
            const result = yield call(queryTag, payload);
            if (result.code === 0) {
                yield put({ type: "updateState", payload: { tagList: result.data } });
            }
            else {
                message.error(result.message, 2);
            }
        },
        *queryAllArticle({ payload }, { put, call, select }) {
            const result = yield call(queryAllArticle, payload);
            if (result.code === 0) {
                yield put({ type: "updateState", payload: { articleList: result.data.records, total: result.data.total } });
            }
            else {
                message.error(result.message, 3);
            }
        },
        *queryArticles({ payload }, { put, call, select }) {
            const result = yield call(queryArticles, payload);
            if (result.code === 0) {
                yield put({ type: "updateState", payload: { articleList: result.data.records, total: result.data.total } });
            }
            else {
                message.error(result.message, 3);
            }
        },
        *viewArticle({payload},{call}){
            yield call(viewArticle,payload);
        },
    },
    reducers: {
        updateState(state, action) {
            return { ...state, ...action.payload };
        }
    }
};